# Confidence interval for Poisson variables
ci.poisson <- function(x, person.time, precision,  alpha=.05, ...){
  count <- x
  incidence <- count/person.time
  if(missing(precision)){
    precision <- incidence/1000
    precision[incidence==0] <- 0.001/person.time[incidence==0] 
  }
  lamda <- incidence * person.time
  for(i in 1:length(count)){
    while(ppois(count[i], lamda[i], lower.tail=TRUE) > alpha/2){
      incidence[i] <- incidence[i] + precision[i]
      lamda[i] <- incidence[i] * person.time[i]
    }}
  ul <- incidence
  
  incidence <- count/person.time
  lamda <- incidence * person.time
  count1 <- count-1
  count1[count==0] <- count[count==0]
  for(i in 1:length(count)){
    while(ppois(count1[i], lamda[i], lower.tail=FALSE) > alpha/2){
      incidence[i] <- incidence[i] - precision[i]
      lamda[i] <- incidence[i] * person.time[i]
    }}
  ll <- incidence
  data.frame.a <- data.frame(events=count,person.time=person.time,incidence=count/person.time, se=sqrt(count)/person.time, ll=ll, ul=ul)
  names(data.frame.a)[5] <- paste("exact.lower",100*(1-alpha),"ci",sep="")
  names(data.frame.a)[6] <- paste("exact.upper",100*(1-alpha),"ci",sep="")
  if(nrow(data.frame.a)==1){rownames(data.frame.a) <- ""}
  data.frame.a
}